package com.changpay.zywy.ui.activity.main
import android.Manifest
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Environment
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import com.changpay.zywy.R
import com.changpay.zywy.base.BaseMvpActivity
import com.changpay.zywy.bean.ImgBg
import com.changpay.zywy.bean.QrInfoBean
import com.changpay.zywy.constant.Constant
import com.changpay.zywy.ext.showToast
import com.changpay.zywy.help.PermissionHelper
import com.changpay.zywy.mvp.contract.QrContract
import com.changpay.zywy.mvp.presenter.QrPresenter
import com.changpay.zywy.utils.ImageLoader
import com.changpay.zywy.utils.ImageUtil
import com.changpay.zywy.utils.Preference
import com.changpay.zywy.utils.SaveViewToImageUtil
import kotlinx.android.synthetic.main.activity_qr_code.*
import kotlinx.android.synthetic.main.activity_qr_code.qr_iv_bg
import kotlinx.android.synthetic.main.activity_qr_code.qr_iv_code
import kotlinx.android.synthetic.main.activity_qr_code.qr_iv_head
import kotlinx.android.synthetic.main.activity_qr_code.qr_tv_invite_code
import kotlinx.android.synthetic.main.activity_qr_code.qr_tv_member_name
import kotlinx.android.synthetic.main.activity_qr_code.rlQrBg
import kotlinx.android.synthetic.main.activity_qr_code.tv_more
import org.jetbrains.anko.sdk27.coroutines.onClick
import java.io.File

class QRCodeActivity : BaseMvpActivity<QrContract.View, QrContract.Presenter>(), QrContract.View {
    private var mPopupWindow: PopupWindow? = null
    private var infoBean: QrInfoBean? = null
    private var bgBeanList: List<ImgBg> = mutableListOf()
    private var currentBg = 0

    private var head_image: String by Preference(Constant.HEAD_IMAGE, "")
    private var old_bg: String by Preference(Constant.CURRE_QR_BG, "")
    private var true_name: String by Preference(Constant.TRUE_NAME, "")
    private var approve: Int by Preference(Constant.IS_APPROVE, 0)
    override fun createPresenter(): QrContract.Presenter  = QrPresenter()

    override fun attachLayoutRes(): Int  = R.layout.activity_qr_code

    override fun initData() {
    }

    override fun initView() {
        super.initView()
        tv_more.setOnClickListener {
            more()
        }
        iv_back.onClick { finish() }
    }

    override fun start() {
        mPresenter?.getQrInfo(token)
    }

    override fun showQrInfo(date: QrInfoBean) {
        ImageLoader.load(date.info.qrcode_url, qr_iv_code)
        ImageLoader.loadAvatar(date.info.member_avatar, qr_iv_head)
        qr_tv_invite_code.text = "邀请码：" + date.info.inviter_code
        val name = date.info.member_name
        if (name.isEmpty())  //为空时先去判断是否实名认证
        {
            if (approve == 0) {
                qr_tv_member_name.text = "请先实名认证"
            } else {
                qr_tv_member_name.text = true_name
            }
        } else {
            qr_tv_member_name.text = date.info.member_name
        }
        infoBean = date
        bgBeanList = date.img_bg_list
        loadQrBg()
    }

    private fun more() {
        if (mPopupWindow == null) {
            val popView = View.inflate(this, R.layout.more_layout, null)
            mPopupWindow =
                PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
            mPopupWindow!!.isOutsideTouchable = true
            val dw = ColorDrawable(Color.parseColor("#00000000"))
            // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
            // 我觉得这里是API的一个bug
            mPopupWindow!!.setBackgroundDrawable(dw)
            popView.findViewById<View>(R.id.save_image).setOnClickListener { view ->
                PermissionHelper.instance.getPermission(
                    this, object : PermissionHelper.PermissionCallBack {
                        override fun onSuccess() {
                            val viewBitmap = SaveViewToImageUtil.getViewBitmap(rlQrBg)
                            val storePath =
                                Environment.getExternalStorageDirectory().absolutePath + File.separator + "kdb"
                            val fileName = System.currentTimeMillis().toString() + ".jpg"
                            val b = ImageUtil.saveImageToGallery(this@QRCodeActivity, viewBitmap!!, storePath, fileName)
                            if (b) {
                                showToast("保存成功")
                                mPopupWindow!!.dismiss()
                            }

                        }

                        override fun onFail() {
                            showToast("获取权限失败")
                        }
                    }, Manifest.permission.WRITE_EXTERNAL_STORAGE
                )


            }
            popView.findViewById<View>(R.id.change_bg).setOnClickListener { view ->
                changeBg()
                mPopupWindow!!.dismiss()
            }
            // 分享微信
            popView.findViewById<View>(R.id.tv_share_weChat).setOnClickListener { view ->
                showToast("功能暂未开放")
//                val shareBean =
//                    ShareBean("开店宝", "邀请分享", head_image, infoBean?.info?.html_url)
//                ShareHelper.INSTANCE.shareToWeChat(this, shareBean)
//                mPopupWindow!!.dismiss()
            }
            // 分享朋友圈
            popView.findViewById<View>(R.id.tv_share_weChat_fiend).setOnClickListener { view ->
                showToast("功能暂未开放")
//                val shareBean =
//                    ShareBean("开店宝", "邀请分享", head_image, infoBean?.info?.html_url)
//                ShareHelper.INSTANCE.shareToWeChatFriend(this, shareBean)
//                mPopupWindow!!.dismiss()
            }
        }
        mPopupWindow!!.showAsDropDown(tv_more)
    }

    private fun changeBg() {
        val size = bgBeanList.size
        val i = currentBg + 1
        if (i > size - 1)
        // 加载第一个
        {
            currentBg = 0
            old_bg = bgBeanList[0].adv_id
            ImageLoader.loadImage(qr_iv_bg, bgBeanList[0].adv_code)
        } else {
            currentBg = i
            old_bg = bgBeanList[i].adv_id
            ImageLoader.loadImage(qr_iv_bg, bgBeanList[i].adv_code)
        }
    }


    /**
     * 加载背景图片
     */
    private fun loadQrBg() {
        // 1 读取缓存中的数据
        if (TextUtils.isEmpty(old_bg))
        // 为空
        {
            // 写入背景id
            val qrBgBean = bgBeanList[0]
            old_bg = qrBgBean.adv_id
            ImageLoader.loadImage(qr_iv_bg, qrBgBean.adv_code)
            currentBg = 0
        } else {
            // 查找当前list中是否有保存id
            for (i in bgBeanList.indices) {
                val bgBean = bgBeanList[i]
                if (bgBean.adv_id == old_bg) {
                    currentBg = i
                    old_bg = bgBean.adv_id
                    ImageLoader.loadImage(qr_iv_bg, bgBean.adv_code)
                    break
                }
            }
        }
    }
    

}
